package com.xie.smfs.item;

import net.minecraft.entity.Entity;
import net.minecraft.entity.Entity.RemovalReason;

import com.xie.smfs.entity.GhostEntity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.world.World;

public class GoldenContainerItem extends Item {
    public static final String GHOST_NBT_KEY = "ContainedGhost";
    public static final String HAS_GHOST_NBT_KEY = "HasGhost";

    public GoldenContainerItem(Settings settings) {
        super(settings);
    }

    @Override
    public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity entity, Hand hand) {
        // 仅在服务端处理逻辑
        if (user.getWorld().isClient) {
            return ActionResult.SUCCESS;
        }

        // 检查目标是否为被压制的鬼且容器为空
        if (entity instanceof GhostEntity ghost && !hasGhost(stack)) {
            if (ghost.isSuppressed() && ghost.hasCoffinNail()) {
                captureGhost(stack, ghost, user);
                return ActionResult.SUCCESS;
            }
        }

        return ActionResult.PASS;
    }

    @Override
    public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
        ItemStack stack = user.getStackInHand(hand);

        // 仅在服务端处理逻辑
        if (world.isClient) {
            return TypedActionResult.success(stack);
        }

        // 如果容器中有鬼，则释放
        if (hasGhost(stack)) {
            releaseGhost(stack, user, world);
            return TypedActionResult.success(stack);
        }

        return TypedActionResult.pass(stack);
    }

    private boolean hasGhost(ItemStack stack) {
        return stack.getOrCreateNbt().getBoolean(HAS_GHOST_NBT_KEY);
    }

    @Override
    public String getTranslationKey(ItemStack stack) {
        if (hasGhost(stack)) {
            return "item.smfs.golden_container.full";
        } else {
            return "item.smfs.golden_container.empty";
        }
    }

    @Override
    public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
        super.inventoryTick(stack, world, entity, slot, selected);
        if (entity instanceof PlayerEntity player && !world.isClient && hasGhost(stack) && selected) {
            player.addStatusEffect(new StatusEffectInstance(StatusEffects.SLOWNESS, 0, 0, false, false));
        }
    }

    private void captureGhost(ItemStack stack, GhostEntity ghost, PlayerEntity player) {
        if (hasGhost(stack)) {
        return;
    }
    World world = player.getWorld();

    // 保存鬼的NBT数据
    NbtCompound ghostNbt = new NbtCompound();
ghost.writeNbt(ghostNbt);
ghostNbt.put("CoffinNail", ghost.getCoffinNail().writeNbt(new NbtCompound()));
    stack.getOrCreateNbt().put(GHOST_NBT_KEY, ghostNbt);
    // 清除UUID信息防止实体ID冲突
    ghostNbt.remove("UUID");
    ghostNbt.remove("UUIDMost");
    ghostNbt.remove("UUIDLeast");
    // 确保实体ID标签存在
    ghostNbt.putString("id", EntityType.getId(ghost.getType()).toString());
    stack.getOrCreateNbt().putBoolean(HAS_GHOST_NBT_KEY, true);

        // 移除原鬼实体
        ghost.discard();
        world.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.BLOCK_CHEST_CLOSE, SoundCategory.PLAYERS, 0.5F, 1.0F);
    }

    private void releaseGhost(ItemStack stack, PlayerEntity player, World world) {
        NbtCompound ghostNbt = stack.getOrCreateNbt().getCompound(GHOST_NBT_KEY);

        // 创建新的鬼实体
        // 加载实体并获取返回值
        Entity entity = EntityType.loadEntityWithPassengers(ghostNbt, world, loadedEntity -> {
            loadedEntity.setPos(player.getX(), player.getY(), player.getZ());
            return loadedEntity;
        });
        if (entity != null) {
            world.spawnEntity(entity);
            // 释放后清除压制状态
            if (entity instanceof GhostEntity) {
                GhostEntity releasedGhost = (GhostEntity) entity;
                releasedGhost.readNbt(ghostNbt);
            // 设置生成位置为玩家当前位置
            releasedGhost.setPos(player.getX(), player.getY(), player.getZ());
            // 释放时禁用鬼域
            releasedGhost.disableGhostDomain();
            // 释放时禁用杀人规则
            releasedGhost.disableKillingRules();
                if (ghostNbt.contains("CoffinNail")) {
                    ItemStack coffinNail = ItemStack.fromNbt(ghostNbt.getCompound("CoffinNail"));
                    releasedGhost.setCoffinNail(coffinNail);
                    // 如果有棺材钉则设置为压制状态
                    if (!coffinNail.isEmpty()) {
                        releasedGhost.setSuppressed(true);
                    }
                }

            }
        }

        // 清空容器
        stack.getOrCreateNbt().remove(GHOST_NBT_KEY);
        stack.getOrCreateNbt().putBoolean(HAS_GHOST_NBT_KEY, false);

        world.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.BLOCK_CHEST_OPEN, SoundCategory.PLAYERS, 0.5F, 1.0F);
    }
}